from tornado.websocket import WebSocketHandler

from game.player import Player
from game.dispatcher import Dispatcher

import json
import logging

logger = logging.getLogger(__name__)

class GameHandler(WebSocketHandler, Dispatcher):
    player = None
    def send(self, message):
        try:
            self.write_message(json.dumps(message))
        except Exception, e:
            logger.error(e)

    def open(self):
        logger.debug('ws.open')
        self.set_nodelay(True)
        if 'player' in self.cookies:
            player_id = self.cookies['player'].value
        else:
            player_id = self.get_argument('player', None)
        player = Player.get(player_id)
        if not player:
            player = Player()
        self.player = player
        self.player.connect(self)

    def on_message(self, message):
        logger.debug('ws.msg %s', message)
        try:
            self.player.recv(json.loads(message))
        except Exception, e:
            logger.error(e)

    def on_close(self):
        logger.debug('ws.close')
        self.player.disconnect()
        self.player = None

